import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
import CryptoJS from 'crypto-js'

const rsaPublicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOTBfQ6Q4all8yecWy+ulyGLfPTofE37LvL3h0sw5TJ630DYz47ETvTq3QQhuH6pTpqtyhGBBdjDCmm37EGgdYUCAwEAAQ=='

// 获取随机字符串
function randomString(e) {
  e = e || 32;
  // eslint-disable-next-line prefer-const
  let t = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
    // eslint-disable-next-line prefer-const
    a = t.length,
    n = '';
  for (let i = 0; i < e; i++) {
    n += t.charAt(Math.floor(Math.random() * a));
  }
  return n;
}

function getRondomKey(e) {
  const str = randomString(e)
  return str;
}

// RSA加密
function rsaEncrypt(txt) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(rsaPublicKey) // 设置公钥
  return encryptor.encrypt(txt) // 对数据进行加密
}

function aesEncrypt(randomKey, data, iv) {
  const encrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(randomKey), {
    iv: CryptoJS.enc.Utf8.parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

export {
  getRondomKey,
  rsaEncrypt,
  aesEncrypt
}
